package com.cafe.pro.util;

import org.apache.commons.lang3.StringUtils;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.Base64;

/**
 * 通用加解密工具
 *
 * @author cafe
 * @version 1.0
 * @since 2025-06-08 17:00:00
 */


public class CryptoUtils {

    // AES相关配置
    private static final String AES_ALGORITHM = "AES";
    private static final String AES_TRANSFORMATION = "AES/CBC/PKCS5Padding";

    /**
     * AES加密
     *
     * @param data 待加密数据
     * @param key  AES密钥
     * @return 加密后的数据（Base64编码）
     * @throws Exception 加密异常
     */
    public static String aesEncrypt(String data, String key) throws Exception {
        SecretKeySpec secretKey = new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), AES_ALGORITHM);
        IvParameterSpec iv = new IvParameterSpec(key.getBytes());
        Cipher cipher = Cipher.getInstance(AES_TRANSFORMATION);
        cipher.init(Cipher.ENCRYPT_MODE, secretKey, iv);
        byte[] encryptedData = cipher.doFinal(data.getBytes(StandardCharsets.UTF_8));
        return Base64.getEncoder().encodeToString(encryptedData);
    }

    /**
     * AES解密
     *
     * @param encryptedData 加密后的数据（Base64编码）
     * @param key           AES密钥
     * @return 解密后的数据
     * @throws Exception 解密异常
     */
    public static String aesDecrypt(String encryptedData, String key) throws Exception {
        SecretKeySpec secretKey = new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), AES_ALGORITHM);
        IvParameterSpec iv = new IvParameterSpec(key.getBytes());
        Cipher cipher = Cipher.getInstance(AES_TRANSFORMATION);
        cipher.init(Cipher.DECRYPT_MODE, secretKey, iv);
        byte[] decodedData = Base64.getDecoder().decode(encryptedData);
        byte[] decryptedData = cipher.doFinal(decodedData);
        return new String(decryptedData);
    }

    /**
     * 从ThirdSession请求头中提取aeskey
     *
     * @param authorization 请求头
     *                           格式：Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJVadQssw5c
     * @return
     */
    public static String extractAesKey(String authorization) {
        if (StringUtils.isEmpty(authorization)) {
            return null;
        }
        StringBuilder result = new StringBuilder(authorization.substring(authorization.length() - 16));
        // 长度大于16位，截取前16位
        if (result.length() > 16) {
            return result.substring(0, 16);
        } else if (result.length() < 16) {
            // 长度小于16位，补齐1
            result.append("1".repeat(Math.max(0, 16 - result.length())));
        }
        return result.toString();
    }


    public static void main(String[] args) throws Exception {
        String header = "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJVadQssw5c";

        String aesKey = extractAesKey(header);
        System.out.println("aesKey:" + aesKey);
        String content = "hello world";
        assert aesKey != null;
        String encrypt = aesEncrypt(content, aesKey);
        System.out.println("encrypt by aes:" + encrypt);
        String decrypt = aesDecrypt(encrypt, aesKey);
        System.out.println("decrypt by aes:" + decrypt);
    }
}
